import { ref, onMounted, onUnmounted } from 'vue'
import { throttle } from 'underscore'
// export function useScroll(cb) {
//   const scrollListenerHandler = () => {
//     const scrollHeight = document.documentElement.scrollHeight;
//     const scrollTop = document.documentElement.scrollTop;
//     const clientHeight = document.documentElement.clientHeight
//     // console.log(document.documentElement.scrollHeight);
//     // console.log(document.documentElement.scrollTop);
//     // console.log(document.documentElement.clientHeight);
//     let flag = ref(false)
//     if (scrollHeight <= scrollTop + clientHeight) {
//       console.log('到底了');
//       if (cb) cb()
//     }
//   }
//   onMounted(() => {
//     window.addEventListener('scroll', scrollListenerHandler)
//   })
//   onUnmounted(() => {
//     window.removeEventListener("scroll", scrollListenerHandler)
//   })
// }
// 方法2,返回一个变量的形式
export function useScroll() {
  let flag = ref(false)
  let scrollHeight = ref(0)
  let scrollTop = ref(0)
  let clientHeight = ref(0)
  const scrollListenerHandler = throttle(() => {
    scrollHeight.value = document.documentElement.scrollHeight;
    scrollTop.value = document.documentElement.scrollTop;
    clientHeight.value = document.documentElement.clientHeight;
    // console.log(1);
    // console.log(document.documentElement.scrollHeight);
    // console.log(document.documentElement.scrollTop);
    // console.log(document.documentElement.clientHeight);
    // console.log('滚动了');
    if (scrollTop.value + clientHeight.value >= scrollHeight.value) {
      // console.log('到底了');
      flag.value = true
    }
  }, 500)
  onMounted(() => {
    window.addEventListener('scroll', scrollListenerHandler)
  })
  onUnmounted(() => {
    window.removeEventListener("scroll", scrollListenerHandler)
  })
  return { flag, scrollTop }
}
